<template>
  <div class="room-list">
    <div class="header">
      <h2>房间列表</h2>
      <el-button type="primary" @click="handleCreateRoom">创建房间</el-button>
    </div>

    <el-table :data="rooms" style="width: 100%">
      <el-table-column prop="roomCode" label="房间号" width="120" />
      <el-table-column label="当前人数" width="100">
        <template #default="{ row }">
          {{ row.playerCount || 0 }}/4
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button 
            type="primary" 
            size="small" 
            @click="handleJoinRoom(row)"
            :disabled="row.status !== 'WAITING' || row.playerCount >= 4"
          >
            加入
          </el-button>
          <el-button 
            type="danger" 
            size="small" 
            @click="handleDeleteRoom(row)"
            v-if="row.creatorId === userId"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 添加空数据提示 -->
    <el-empty 
      v-if="rooms.length === 0" 
      description="暂无可用房间" 
      class="empty-rooms"
    >
      <el-button type="primary" @click="handleCreateRoom">创建房间</el-button>
    </el-empty>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { roomApi } from '@/api/room'
import type { Room } from '@/types/room'

const router = useRouter()
const rooms = ref<Room[]>([])
const userId = ref<number>(0)

const loadRooms = async () => {
  try {
    const res = await roomApi.getAvailableRooms()
    if (res.code === 200) {
      rooms.value = res.data
      console.log('房间数据:', rooms.value)
    }
  } catch (error) {
    console.error('Failed to load rooms:', error)
  }
}

const handleCreateRoom = async () => {
  try {
    const res = await roomApi.createRoom()
    if (res.code === 200) {
      ElMessage.success('创建房间成功')
      await loadRooms()
    }
  } catch (error) {
    console.error('Failed to create room:', error)
  }
}

const handleJoinRoom = async (room: Room) => {
  try {
    const res = await roomApi.joinRoom(room.roomCode)
    if (res.code === 200) {
      ElMessage.success('加入房间成功')
      router.push(`/game/${room.roomCode}`)
    }
  } catch (error) {
    console.error('Failed to join room:', error)
  }
}

const handleDeleteRoom = async (room: Room) => {
  try {
    await ElMessageBox.confirm('确定要删除该房间吗？', '提示', {
      type: 'warning'
    })
    const res = await roomApi.deleteRoom(room.roomCode)
    if (res.code === 200) {
      ElMessage.success('删除房间成功')
      await loadRooms()
    }
  } catch (error) {
    console.error('Failed to delete room:', error)
  }
}

// 格式化日期
const formatDate = (dateStr: string | Date | undefined) => {
  if (!dateStr) return '未知时间';
  
  try {
    const date = new Date(dateStr);
    if (isNaN(date.getTime())) return '无效日期';
    
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  } catch (e) {
    console.error('日期格式化错误:', e);
    return '日期错误';
  }
}

const getStatusType = (status: string) => {
  switch (status) {
    case 'WAITING':
      return 'success'
    case 'PLAYING':
      return 'warning'
    case 'FINISHED':
      return 'info'
    default:
      return ''
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'WAITING':
      return '等待中'
    case 'PLAYING':
      return '游戏中'
    case 'FINISHED':
      return '已结束'
    default:
      return status
  }
}

onMounted(() => {
  // 从localStorage获取用户ID
  const token = localStorage.getItem('token');
  if (token) {
    try {
      const tokenData = JSON.parse(atob(token.split('.')[1]));
      if (tokenData && tokenData.userId) {
        userId.value = tokenData.userId;
      }
    } catch (e) {
      console.error('解析token失败:', e);
    }
  }
  
  loadRooms()
})
</script>

<style scoped>
.room-list {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.empty-rooms {
  margin-top: 40px;
}
</style> 